import React from 'react';
import { Button, Form,Radio, Input, Row, Col,message,InputNumber  } from 'antd';
import $ from 'jquery';
import classNames from 'classnames';
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const createForm = Form.create;
const FormItem = Form.Item;
import { register } from '../store/actions';
import {  connect } from 'react-redux';
require('../../css/form-register.css');

function noop() {
    return false;
}
class __FormRegister extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false,
            passStrength: 'L', // 密码强度
            rePassStrength: 'L'
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.getPassStrenth = this.getPassStrenth.bind(this);
        this.renderPassStrengthBar = this.renderPassStrengthBar.bind(this);
        this.checkPass = this.checkPass.bind(this);
        this.checkPass2 = this.checkPass2.bind(this);
        this.handleBack = this.handleBack.bind(this);
        //this.checkUserName = this.checkUserName.bind(this);
    }
    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        _this.props.form.validateFields((errors, values) => {
            if (!!errors) {
                message.warning('表单填写错误',1);
                return;
            }
            delete values.rePass;
            _this.props.dispatch(register(values,function(res){
                message.success('注册成功，请登录',1,function(){
                    _this.props._r.push('/login');
                });
            },function(res){
                message.error(res.head.msg,1)
            }))
        });
    }
    handleBack() {
        this.props._r.push('/login',{hasLogin:false});
    }
    getPassStrenth(value, type) {
        if (value) {
            let strength;
            // 密码强度的校验规则自定义，这里只是做个简单的示例
            if (value.length < 6) {
                strength = 'L';
            } else if (value.length <= 9) {
                strength = 'M';
            } else {
                strength = 'H';
            }
            if (type === 'password') {
                this.setState({ passBarShow: true, passStrength: strength });
            } else {
                this.setState({ rePassBarShow: true, rePassStrength: strength });
            }
        } else {
            if (type === 'pass') {
                this.setState({ passBarShow: false });
            } else {
                this.setState({ rePassBarShow: false });
            }
        }
    }

    checkPass(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'password');
        if (form.getFieldValue('password')) {
            form.validateFields(['rePass'], { force: true });
        }
        callback();
    }

    checkPass2(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'rePass');

        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }

    renderPassStrengthBar(type) {
        const strength = type === 'pass' ? this.state.passStrength : this.state.rePassStrength;
        const classSet = classNames({
            'ant-pwd-strength': true,
            'ant-pwd-strength-low': strength === 'L',
            'ant-pwd-strength-medium': strength === 'M',
            'ant-pwd-strength-high': strength === 'H'
        });
        const level = {
            L: '低',
            M: '中',
            H: '高'
        };

        return (
            <div>
                <ul className={classSet}>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-1"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-2"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-3"> </li>
          <span className="ant-form-text">
            {level[strength]}
          </span>
                </ul>
            </div>
        );
    }

    checkUserName(rule, value, callback){
        const _reg = /^[a-zA-Z\d]\w{4,18}[a-zA-Z\d]$/;
        const _regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        const result = _reg.test(value);
        const result2 = _regEmail.test(value);
        if (!result && !result2) {
           callback('6-20位，不能包含汉字和特殊字符，可以是email或手机号')
        } else {
            callback();
        }
    }
    checkMob(rule, value, callback){
        const _reg = /^1[3|4|5|7|8]\d{9}$/,
            result = _reg.test(value);
        if (!result && value) {
           callback('请输入正确格式的手机号')
        } else {
            callback();
        }
    }
    componentDidMount(){
        $('#formContent').height($(window).height()-110);
        $(window).resize(function(){
            $('#formContent').height($(window).height()-110);
        })
        //rules
        const _this = this;
        this.props.dispatch(check_rules(function(rules){
            _this.setState({
                rules:rules.content
            })
        }));
    }
    render(){
        const { getFieldProps} = this.props.form;
        const usernameProps = getFieldProps('username', {
            rules: [
                { required: true, message: '请输入用户名' },
                { validator: this.checkUserName }
            ],
            validateTrigger:'onBlur'
        });
        const passProps = getFieldProps('password', {
            rules: [
                { required: true,whitespace: true,message: '请输入密码' },
                { min:6,max:20,message: '密码为6-20位' },
                { validator: this.checkPass }
            ]

        });
        const rePassProps = getFieldProps('rePass', {
            rules: [{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
            }, {
                validator: this.checkPass2
            }]
        });
        const idCardProps = getFieldProps('idcard', {
            rules: [
                { required: true, message: '请输入身份证号' },
                { min:18, max: 18, message: '身份证号是18位' }
            ]
        });
        const mobProps = getFieldProps('mobile', {
            rules: [
                { required: true, message: '请输入手机号' },
                { validator: this.checkMob }
            ]
        });
        const nickProps = getFieldProps('nickname', {
            rules: [
                { required: false,max:16, message: '昵称不得超过16个字' }
            ]
        });
        const nameProps = getFieldProps('name', {
            rules: [
                { required: false,max:16, message: '姓名不得超过16个字' }
            ]
        });
        const genderProps = getFieldProps('gender', {
            rules: [
                { required: false, message: '请选择性别' }
            ]
        });
        const emailProps = getFieldProps('mail', {
            validate: [{
                rules: [
                    { required: true,message:'请输入邮箱地址' }
                ]
            }, {
                rules: [
                    { type: 'email', message: '请输入正确的邮箱地址' }
                ],
                trigger: ['onBlur', 'onChange']
            }]
        });
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 }
        };
        return (
            <div id="formContent" style={{
                overflow:'auto'
            }}>
                <h2 id="accessFormTitle">免费注册</h2>
                <Form horizontal form={this.props.form}>
                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="用户名"
                            >
                                <Input {...usernameProps} placeholder="请输入用户名" style={{width:'100%'}} />
                            </FormItem>
                        </Col>
                        <Col span="6">
                        </Col>
                    </Row>

                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="密码"
                            >
                                <Input {...passProps} type="password"
                                  onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                                  autoComplete="off" id="password"
                                />
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="确认密码"
                            >
                                <Input {...rePassProps} type="password"
                                  onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                                  autoComplete="off" id="rePass"
                                />
                            </FormItem>
                        </Col>
                        <Col span="6">
                            {this.state.passBarShow ? this.renderPassStrengthBar('pass') : null}
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <Col span="6"> </Col>
                            <Col span="18" style={{padding:'0 0 20px'}}>以下为个人资料，建议认真填写</Col>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">

                            <FormItem
                                label="身份证号"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                            >
                                <Input {...idCardProps} placeholder="请输入身份证号" />
                            </FormItem>
                            <FormItem
                              label="手机号"
                              labelCol={{ span: 6 }}
                              wrapperCol={{ span: 18 }}
                            >
                                <Input {...mobProps} placeholder="请输入手机号" />
                            </FormItem>
                            <FormItem
                              label="电子邮件"
                              labelCol={{ span: 6 }}
                              wrapperCol={{ span: 18 }}
                            >
                                <Input {...emailProps} placeholder="请输入email" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <FormItem
                                label="姓名"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                            >
                                <Input {...nameProps} placeholder="请输入姓名" />
                            </FormItem>
                            <FormItem
                                label="昵称"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                            >
                                <Input {...nickProps} placeholder="请输入昵称" />
                            </FormItem>
                            <FormItem
                                label="性别"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                            >
                                <RadioGroup {...genderProps}>
                                    <RadioButton value="M">男</RadioButton>
                                    <RadioButton value="F">女</RadioButton>
                                </RadioGroup>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <Col span="18" offset="6">
                                <Button type="primary" onClick={this.handleSubmit}>免费注册</Button>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <Button onClick={this.handleBack}>返回登录</Button>
                            </Col>
                        </Col>
                    </Row>
                </Form>
            </div>
        )
    }

}

const _FormRegister = createForm()(__FormRegister);
let FormRegister;
export default FormRegister = connect((state)=>{
    return state
})(_FormRegister)